<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Connections</title>
</head>
<body>


<table id="c-list" border="1">
    <tr bgcolor="#cccccc">
        <th>登录用户</th>
        <th>连接信息</th>
        <th>是否活动</th>
        <th>操作</th>
    </tr>
</table>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript">
    function WebSocketTest()
    {
        if ("WebSocket" in window)
        {
            // 打开一个 web socket
            var ws = new WebSocket("ws://192.168.10.141:8080/connections");
            ws.onopen = function()
            {
                // Web Socket 已连接上，使用 send() 方法发送数据
                ws.send("发送数据");
            };
            ws.onmessage = function (evt)
            {
                renderConnection(evt.data)
            };
            ws.onclose = function()
            {
                // 关闭 websocket
                alert("连接已关闭...");
            };
        }
        else
        {
            // 浏览器不支持 WebSocket
            alert("您的浏览器不支持 WebSocket!");
        }
    }
    WebSocketTest();

    function renderConnection(json){
        var connections = JSON.parse(json);
        var table = $('#c-list');
        table.find('.connection').remove();
        $.each(connections,function(k,v){
            var tr = '<tr class="connection"> <td class="target">'+v['target']+'</td> <td class="connectionId">'+v['socket']+'</td> <td class="active">'+v['active']+'</td><td><label><input type="text"/><button onclick="pushMessage(this)">推送内容</button></label></label></td> </tr>'
            table.append(tr);
        })
    }

    function pushMessage(dom) {
        var text = $(dom).siblings('input').val();
        var target = $(dom).parents('.connection').find('.target').text();
        var request = {};
        request.text = text;
        request.target = target;
        $.post('/push',request,function(){
            alert('pushed');
        })
    }
</script>
</body>
</html>
